package cn.jit.controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.DataBinder;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.google.gson.Gson;

import cn.jit.po.Exam;
import cn.jit.po.ExamQuestion;
import cn.jit.po.Question;
import cn.jit.po.User;
import cn.jit.po.UserExam;
import cn.jit.po.UserExamVo;
import cn.jit.service.ExamQuestionService;
import cn.jit.service.ExamService;
import cn.jit.service.QuestionService;
import cn.jit.service.UserExamService;
import cn.jit.service.UserService;
import cn.jit.util.MD5Util;
import cn.jit.util.PrintUtil;
import cn.jit.util.RedisUtil;
import cn.jit.util.ResponseObject;
import cn.jit.util.ResponseUtil;
import cn.jit.util.UploadFileUtil;
import cn.jit.validator.UserValidator;
import jdk.nashorn.internal.ir.RuntimeNode.Request;
import net.sf.json.JSONObject;

/**
 * 用户模块
 * @author 1072183582@qq.com
 * 
 */
@Controller
@RequestMapping("/user")
public class UserController {
	
	@Resource
    private UserService userService;
	
	@Resource
	private ExamQuestionService examQuestionService;
	
	@Resource
	private ExamService examService;
	
	@Resource
	private UserExamService userExamService;
	
	@Resource
	private QuestionService questionService;
	
	@InitBinder  
    public void initBinder(DataBinder binder) {  
       binder.setValidator(new UserValidator());
    }
	
	/******************* 前端界面 开始 ********************/
	
	
	@RequestMapping(value="/center",method=RequestMethod.GET)
    public ModelAndView examCenter(HttpServletRequest request) {
		HttpSession session = request.getSession();
		ModelAndView mv = new ModelAndView();
		
		Object object =  session.getAttribute("loginedUserId");
		if (object == null) {
			mv.setViewName("login");
			return mv;
		}

		Integer userId = (Integer)object;
		User user = userService.getUser(userId);
		UserExam userExam = new UserExam();
		userExam.setUserId(userId);
		UserExamVo uExamVo = userExamService.getUserExamList(userExam);
		
		System.out.println("用户" + userId + "的考试: " + uExamVo);
		mv.setViewName("user_center");
		mv.addObject("user", user);
		if (uExamVo != null) {
			mv.addObject("examList", uExamVo.getExamList());
		} else {
			mv.addObject("examList", null);
		}
		
		return mv;
	}
	
	@RequestMapping(value="/start-exam",method=RequestMethod.GET)
    public String startExamPage() {
		return "start_exam";
	}
	
	@RequestMapping(value="/upload-headphoto",method=RequestMethod.GET)
    public String uploadHeadPhotoPage() {
		return "upload_headphoto";
	}
	
	@RequestMapping(value="/update-selfinfo/{userId}",method=RequestMethod.GET)
    public ModelAndView updateSelfInfoPage(@PathVariable Integer userId,HttpServletRequest request) {
		
		ModelAndView mView = new ModelAndView();
		
		//只能查看自己的
		HttpSession session = request.getSession();
		Object obj = session.getAttribute("loginedUserId");
		Integer sessionUserId = (Integer)obj;
		
		System.out.println("userId: " + userId);
		System.out.println("sessionUserId: " + sessionUserId);
		
		if (!sessionUserId.equals(userId)) {
			System.out.println("用户ID与sessionID不等!");
			mView.setViewName("operation_info");
			mView.addObject("info", "只能修改自己的信息啊!");
			return mView;
		}
		
		User user = userService.getUser(userId);
		System.out.println(user);
		
		mView.setViewName("update_selfinfo");
		mView.addObject("user", user);
		return mView;
	}
	
	
	/******************* 前端界面 结束 ********************/
	
	
	/******************* 后端接口 开始 ********************/
	
	@RequestMapping(value="/back_login",method=RequestMethod.POST)
    public void login(User user,String yzm,HttpServletRequest request,HttpServletResponse response) {
		
    	if (yzm != null) {
    		yzm = yzm.trim();
		}
    	
    	if (request.getSession().getAttribute("yzm") == null) {
			ResponseObject resp = new ResponseObject("验证码已过期,请刷新页面!");
			JSONObject respJson = JSONObject.fromObject(resp);
			ResponseUtil.writeJson(response, respJson);
		}
    	
		String sessionYzm = ((String) request.getSession().getAttribute("yzm")).trim();
    	if (!sessionYzm.equals(yzm)) {
    		JSONObject respJson = JSONObject.fromObject(new ResponseObject("验证码不正确"));
    		ResponseUtil.writeJson(response, respJson);
			return ;
		}
    	
		ResponseObject responseObject = new ResponseObject();
		System.out.println("用户输入的验证码:" + yzm);
		responseObject.setCode(200);
		responseObject.setIsSuccess(true);
		responseObject.setMsg("登录成功!");
		
		System.out.println(user);
		
		String MD5Pwd = MD5Util.MD5Encode(user.getPassword(), "UTF-8");
		user.setPassword(MD5Pwd);
		
		System.out.println(user);
		
		User returnUser =  userService.getUserForlogin(user);
		if (returnUser == null) {
			responseObject.setIsSuccess(false);
			responseObject.setMsg("登录失败!");
			responseObject.setData(null);
			JSONObject jsonObject = JSONObject.fromObject(responseObject);
			ResponseUtil.writeJson(response, jsonObject);
			return ;
		}
		
		HttpSession session = request.getSession();
		session.setAttribute("loginedUsername", returnUser.getUsername());
		session.setAttribute("loginedUserId", returnUser.getUserId());
		session.setAttribute("loginedUserType", returnUser.getType());
		session.setAttribute("loginedUserPhotoUrl", returnUser.getPhotoUrl());
		System.out.print("returnUser: ");
		System.out.println(returnUser);
		responseObject.setData(returnUser);
		JSONObject jsonObject = JSONObject.fromObject(responseObject);
		ResponseUtil.writeJson(response, jsonObject);
		return ;
    }
	
	@RequestMapping(value="/back_register",method=RequestMethod.POST)
    public void register(@Valid User user, 
    		BindingResult bindingResult,
    		HttpServletRequest request, 
    		HttpServletResponse response) {
		
		ResponseObject responseObject = new ResponseObject();
		
		if(bindingResult.hasErrors()){  
			StringBuffer sb = new StringBuffer();
	        for(ObjectError objectError : bindingResult.getAllErrors()){  
	            sb.append(objectError.getDefaultMessage()).append("; ");
	        }  
	        responseObject.setCode(400);
	        responseObject.setIsSuccess(false);
	        responseObject.setData(new String(sb.toString()));
	        responseObject.setMsg(sb.toString());
	        JSONObject jsonObject = JSONObject.fromObject(responseObject);
			ResponseUtil.writeJson(response, jsonObject);
	        return ;
		}
		
		System.out.println(user);
		
		String username = request.getParameter("username");
		String truename = request.getParameter("truename");
		System.out.println("username: " + username);
		System.out.println("truename: " + truename);
		String code = request.getParameter("code");
		System.out.println("code: " + code);
		
		String redisEmailCode = RedisUtil.get(user.getEmail()+"_code");
		
		if (!redisEmailCode.equals(code)) {
			ResponseObject resp = new ResponseObject("验证码不正确!");
			ResponseUtil.writeJson(response, new Gson().toJson(resp));
			return ;
		}
		
		String MD5Pwd = MD5Util.MD5Encode(user.getPassword(), "UTF-8");
		user.setPassword(MD5Pwd);
		
		user.setCreateTime(new Date());
		user.setType(2);
		user.setIsActive(1);
		
		System.out.println(user);
		
		int addResult = userService.addUser(user);
		
		System.out.println(addResult);
		
		
		/** 返回 **/
		if (addResult > 0) {
			responseObject.setCode(200);
			responseObject.setIsSuccess(true);
			responseObject.setMsg("注册成功!");
			responseObject.setData(new Object());
			JSONObject jsonObject = JSONObject.fromObject(responseObject);
			ResponseUtil.writeJson(response, jsonObject);
			return ;
		} else {
			responseObject.setCode(200);
			responseObject.setIsSuccess(false);
			responseObject.setMsg("注册失败!");
			responseObject.setData(new Object());
			JSONObject jsonObject = JSONObject.fromObject(responseObject);
			ResponseUtil.writeJson(response, jsonObject);
			return ;
		}
		
    }
	
	@RequestMapping(value="/back_delete",method=RequestMethod.POST)
    public void delUser(User user,HttpServletRequest request,HttpServletResponse response) {
		ResponseObject responseObject = new ResponseObject();
		Integer userId = user.getUserId();
		User queryUser = new User();
		if (userId == null) {
			responseObject.setCode(200);
			responseObject.setMsg("缺少userId");
			responseObject.setIsSuccess(false);
			JSONObject jsonObject = JSONObject.fromObject(responseObject);
			ResponseUtil.writeJson(response, jsonObject);
			return ;
		}
		
		queryUser.setUserId(userId);
		int result = userService.deleteUserLogically(queryUser);
		
		if (result == 0) {
			responseObject.setCode(200);
			responseObject.setIsSuccess(false);
			responseObject.setMsg("删除失败!");
			JSONObject jsonObject = JSONObject.fromObject(responseObject);
			ResponseUtil.writeJson(response, jsonObject);
			return ;
		}
		
		responseObject.setCode(200);
		responseObject.setIsSuccess(true);
		responseObject.setMsg("删除成功!");
		
		JSONObject jsonObject = JSONObject.fromObject(responseObject);
		ResponseUtil.writeJson(response, jsonObject);
		return ;
    }
	
	@RequestMapping(value="/back_update",method=RequestMethod.POST)
    public void updUser(User user,HttpServletRequest request,HttpServletResponse response) {
		System.out.println(user);
		Boolean result = userService.updateUser(user);
		if (!result) {
			JSONObject jsonObject = JSONObject.fromObject(new ResponseObject("修改失败!"));
			ResponseUtil.writeJson(response, jsonObject);
			return;
		}
		ResponseObject responseObject = new ResponseObject();
		responseObject.setCode(200);
		responseObject.setIsSuccess(true);
		responseObject.setMsg("修改成功!");
		JSONObject jsonObject = JSONObject.fromObject(responseObject);
		ResponseUtil.writeJson(response, jsonObject);
		return;
    }
	
	/**
	 * 
	 * @param user
	 * @param request
	 * @param response
	 */
	@RequestMapping(value="/back_start_exam",method=RequestMethod.GET)
    public void startExam(Integer userId,HttpServletRequest request,HttpServletResponse response) {
		// 1. 先在dsts_exam的表中新增一条记录,返回自增的ID
		Exam exam = new Exam();
		exam.setStartTime(new Date());
		exam.setIsActive(0);
		exam.setIsSubmit(0);
		
		int addExamResult = examService.addExam(exam);
		PrintUtil.debugInfo("Exam.startExam()", "新增考试", addExamResult);
		
		if (addExamResult == 0) {
			ResponseUtil.writeJson(response, JSONObject.fromObject(new ResponseObject("新增考试失败!")));
			return ;
		}
		Integer autoIncrId = exam.getExamId();
		
		
		// 2. 然后在dsts_user_exam中新增一条记录
		UserExam userExam = new UserExam();
		userExam.setUserId(userId);
		userExam.setExamId(autoIncrId);
		userExam.setIsActive(1);
		
		Integer addUserExamResult = userExamService.addUserExam(userExam);
		PrintUtil.debugInfo("Exam.startExam()", "新增用户考试", addUserExamResult);
		
		if (addUserExamResult == 0) {
			ResponseUtil.writeJson(response, JSONObject.fromObject(new ResponseObject("新增用户考试失败!")));
			return ;
		}
		
		Question queryQuestion= new Question();
		queryQuestion.setQuestionType(1);
		List<Question> questions = questionService.getQuestions(queryQuestion);
		
		if (questions == null) {
			ResponseUtil.writeJson(response, JSONObject.fromObject(new ResponseObject("开始考试失败!")));
			return ;
		}
		ExamQuestion eq = new ExamQuestion();
		eq.setExamId(autoIncrId);
		eq.setQuestionList(questions);
		ResponseObject respObj = new ResponseObject(eq);
		
		JSONObject respJson = JSONObject.fromObject(respObj);
		ResponseUtil.writeJson(response, respJson);
		return ;
    }
	
	@RequestMapping(value = "/back_upload_headphoto", method = RequestMethod.POST)
	@ResponseBody
	public ModelAndView upload(@RequestParam("image") MultipartFile image, 
							HttpServletRequest request, 
							HttpSession session) throws IOException {
		 ModelAndView mView = new ModelAndView();
		 String userId = request.getParameter("userId");
		 System.out.println("用户ID: " + userId);
		 //上传的目标文件夹
		 String path = request.getSession().getServletContext().getRealPath("/resources/upload");
		 System.out.println("存放的path：" + path);
		 
		 //路径分隔符
		 System.out.println("File.separator:" + File.separator); // 结果是 
		 
		 //原文件名
		 String fileName = image.getOriginalFilename();
		 System.out.println("filename:" + fileName);
		 
		 //新文件名
		 SimpleDateFormat stFormat = new SimpleDateFormat("yyyymmddhhMMSS");
		 String newfileName = stFormat.format(new Date());
		 
		 String suffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
		 System.out.println("上传文件的后缀是:" + suffix);
		 
		 if (!UploadFileUtil.fileSuffixIsAllowed(suffix)) {
			 mView.setViewName("redirect:upload-headphoto");
			 mView.addObject("updErrorInfo","只允许上传jpg、JPG、png、PNG文件");
			 return mView;
		 }
		 
		 newfileName += suffix;
	     System.out.println("新的文件名是:" + newfileName);
	     
	     // 修改用户表
	     StringBuffer photoUrl = new StringBuffer();
	     photoUrl.append("resources").append("/")
	     		.append("upload").append("/").append(newfileName);
		 System.out.println("用户图片的存放路径:" + photoUrl.toString());
		 
		 File dir = new File(path, newfileName);
		 
		 if (!dir.exists()) {
			 System.out.println("文件不存在！要准备创建！");
			 dir.mkdirs();
		 }
		 
		 image.transferTo(dir);
		 
		 User updUser = new User();
		 updUser.setUserId(Integer.parseInt(userId));
		 updUser.setPhotoUrl(photoUrl.toString());
		 if (!userService.updateUser(updUser)) {
			 mView.setViewName("redirect:upload-headphoto");
			 mView.addObject("updErrorInfo","上传失败!");
			 return mView;
		 }
		 
		 mView.setViewName("redirect:center");
		 return mView;
	}
	
	@RequestMapping(value = "/back_logout", method = RequestMethod.GET)
	public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
		request.getSession().invalidate();
		ResponseObject resp = new ResponseObject();
		resp.setCode(200);
		resp.setIsSuccess(true);
		resp.setMsg("退出成功!");
		ResponseUtil.writeJson(response, JSONObject.fromObject(resp));
		return;
	}
	
	@RequestMapping(value = "/back_regetpwd", method = RequestMethod.POST)
	public void reGetPwd(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String email = request.getParameter("email");
		String code = request.getParameter("code");
		String pwd = request.getParameter("pwd");
		String confirmPwd = request.getParameter("confirmPwd");
		ResponseObject resp = new ResponseObject();
		resp.setCode(200);
		resp.setIsSuccess(false);
		
		// 验证邮箱合法性
		if (!email.matches("^\\w+@(\\w+\\.)+\\w+$")) {
			resp.setMsg("邮箱格式有误!");
			ResponseUtil.writeJson(response, JSONObject.fromObject(resp));
			return;
		}
		
		//验证两次密码是否一致
		if (!pwd.equals(confirmPwd)) {
			resp.setMsg("两次密码不一致!");
			ResponseUtil.writeJson(response, JSONObject.fromObject(resp));
			return;
		}
		
		//验证码校验
		String redisEmailCode = RedisUtil.get(email+"_code");
		if (redisEmailCode == null) {
			resp = new ResponseObject("验证码已经过期!");
			ResponseUtil.writeJson(response, JSONObject.fromObject(resp));
			return ;
		} else {
			if (!redisEmailCode.equals(code)) {
				resp = new ResponseObject("验证码不正确!");
				ResponseUtil.writeJson(response, JSONObject.fromObject(resp));
				return ;
			}
		}
				
		String MD5Pwd = MD5Util.MD5Encode(pwd, "UTF-8");
		
		//修改之前检验用户是否存在
		if (!userService.getUser(email)) {
			resp = new ResponseObject("用户不存在,操作失败!");
			ResponseUtil.writeJson(response, JSONObject.fromObject(resp));
			return;
		};
		
		//修改密码
		boolean updateRes = userService.updatePwd(email, MD5Pwd);
		if (!updateRes) {
			resp = new ResponseObject("操作失败!");
			ResponseUtil.writeJson(response, JSONObject.fromObject(resp));
			return;
		}
		
		resp.setIsSuccess(true);
		resp.setMsg("操作成功!");
		ResponseUtil.writeJson(response, JSONObject.fromObject(resp));
		return;
	}
	
	
	
//	@RequestMapping(value="/back_start_exam",method=RequestMethod.GET)
//    public void startExam(Integer userId,HttpServletRequest request,HttpServletResponse response) {
//		
//		
//		// 1. 先在dsts_exam的表中新增一条记录,返回自增的ID
//		Exam exam = new Exam();
//		exam.setStartTime(new Date());
//		exam.setIsActive(1);
//		exam.setIsSubmit(0);
//		
//		int addExamResult = examService.addExam(exam);
//		System.out.println("新增考试");
//		System.out.println(addExamResult);
//		
//		if (addExamResult == 0) {
//			ResponseUtil.writeJson(response, JSONObject.fromObject(new ResponseObject("新增考试失败!")));
//			return ;
//		}
//		Integer autoIncrId = exam.getExamId();
//		
//		
//		// 2. 然后在dsts_user_exam中新增一条记录
//		UserExam userExam = new UserExam();
//		userExam.setUserId(userId);
//		userExam.setExamId(autoIncrId);
//		userExam.setIsActive(1);
//		
//		Integer addUserExamResult = userExamService.addUserExam(userExam);
//		System.out.println("新增用户考试");
//		System.out.println(addUserExamResult);
//		
//		if (addUserExamResult == 0) {
//			ResponseUtil.writeJson(response, JSONObject.fromObject(new ResponseObject("新增用户考试失败!")));
//			return ;
//		}
//		
//		// 3. 在dsts_exam_question中新增多条记录
//		ExamQuestion examQuestion = new ExamQuestion();
//		examQuestion.setExamId(autoIncrId);
//		int addExamQuestionResult = examQuestionService.addExamQuestion(examQuestion);
//		
//		System.out.println("新增考试试题");
//		System.out.println(addExamQuestionResult);
//		
//		if (addExamQuestionResult != 10) {
//			ResponseUtil.writeJson(response, JSONObject.fromObject(new ResponseObject("新增考试问题失败!")));
//			return ;
//		}
//		
//		// 4. 拿到本场考试的题目
//				
//		ExamQuestion eq2 = new ExamQuestion();
//		eq2.setExamId(autoIncrId);
//		ArrayList<ExamQuestion> questions = (ArrayList<ExamQuestion>) examQuestionService.getExamQuestions(eq2);
//		if (questions == null) {
//			ResponseUtil.writeJson(response, JSONObject.fromObject(new ResponseObject("服务器出错了,不能考试,请重试!")));
//			return ;
//		}	
//		ResponseObject respObj = new ResponseObject(questions);
//		JSONObject respJson = JSONObject.fromObject(respObj);
//		ResponseUtil.writeJson(response, respJson);
//		return ;
//    }
	/******************* 后端接口 结束 ********************/
}
